<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-20 09:13:56
 * @LastEditTime: 2022-05-20 20:57:10
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
-->
<template>
  <div class="editor-container">
    <div id="editor-box"></div>
    <div class="bottom">
      <el-button
        type="primary"
        @click="onSubmitClick"
      >{{
        $t('article.commit')
      }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, watch } from 'vue'
import { watchSwitchLang } from '@/utils/i18n'

import E from 'wangeditor'
import i18next from 'i18next'
import { useStore } from 'vuex'
const store = useStore()
// eslint-disable-next-line no-undef
const emits = defineEmits(['submit'])
// eslint-disable-next-line no-undef
const props = defineProps({
  details: {
    type: Object
  }
})

// Editor实例
let editor
// 处理离开页面切换语言导致 dom 无法被获取
let el
onMounted(() => {
  el = document.querySelector('#editor-box')
  initEditor()
})

const onSubmitClick = () => {
  emits('submit', editor.txt.html(), () => {
    editor.txt.html('')
  })
}

const initEditor = () => {
  editor = new E(el)
  editor.config.zIndex = 1
  // 菜单栏提示
  editor.config.showMenuTooltips = true
  editor.config.menuTooltipPosition = 'down'
  editor.config.lang = store.getters.language === 'zh' ? 'zh-CN' : 'en'
  editor.i18next = i18next
  editor.create()
}
watch(() => props.details, (v) => {
  v.content && editor.txt.html(v.content)
}, { immediate: true })

watchSwitchLang(() => {
  const html = editor.txt.html()
  editor.destroy()
  initEditor()
  editor.txt.html(html)
})
</script>

<style lang="scss" scoped>
.editor-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
